package com.we.wfc.common.utils;

import com.we.wfc.common.serialize.CurrentObjectInputStream;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @Description: 序列化工具类
 * @Author:Liangzy(Feeling)
 * @Date:Create in 2019/11/1 5:23 下午
 */
@Slf4j
public class SerializeUtil {

    /**
     * 序列化
     *
     * @param object
     * @return
     */
    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            // 序列化
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {
            log.error("serialize in exception：", e);
        }
        return null;
    }

    /**
     * 反序列化
     *
     * @param bytes
     * @return
     */
    public static Object deserialize(byte[] bytes) {
        if (null == bytes) {
            return null;
        }
        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null;
        try {
            // 反序列化
            bais = new ByteArrayInputStream(bytes);
            ois = new CurrentObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
            log.error("deserialize in exception：", e);
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    log.error("deserialize in exception：", e);
                }
            }
        }
        return null;
    }
}
